/**
 * Workers Demo
 * 
 * Demonstrates parallel execution using Bun Workers
 */

// Set test environment to skip API key validation
process.env.NODE_ENV = 'test';

import { workerManager } from '../src/workers';
import { logger } from '../src/utils/logger';

/**
 * Demo: Single Query Execution
 */
async function demoSingleQuery() {
  console.log('\n=== Demo: Single Query Execution ===\n');

  try {
    await workerManager.initialize();

    const result = await workerManager.executeAgentQuery(
      'What is 2 + 2?',
      {
        model: 'claude-sonnet-4',
        maxTurns: 1,
      }
    );

    console.log('Result:', result);
  } catch (error) {
    console.error('Error:', error);
  }
}

/**
 * Demo: Parallel Query Execution
 */
async function demoParallelQueries() {
  console.log('\n=== Demo: Parallel Query Execution ===\n');

  try {
    await workerManager.initialize();

    const queries = [
      { prompt: 'What is 2 + 2?' },
      { prompt: 'What is 3 * 3?' },
      { prompt: 'What is 10 / 2?' },
    ];

    console.log(`Executing ${queries.length} queries in parallel...`);

    const startTime = Date.now();
    const results = await workerManager.executeAgentQueriesParallel(queries);
    const duration = Date.now() - startTime;

    console.log('\nResults:');
    results.forEach((result, index) => {
      console.log(`\nQuery ${index + 1}: ${queries[index].prompt}`);
      console.log(`Result: ${result}`);
    });

    console.log(`\nTotal duration: ${duration}ms`);
    console.log(`Average per query: ${(duration / queries.length).toFixed(2)}ms`);
  } catch (error) {
    console.error('Error:', error);
  }
}

/**
 * Demo: Worker Statistics
 */
async function demoStatistics() {
  console.log('\n=== Demo: Worker Statistics ===\n');

  try {
    await workerManager.initialize();

    // Execute some queries
    await workerManager.executeAgentQuery('Hello!');

    // Get statistics
    const stats = workerManager.getStatistics();

    console.log('Worker Statistics:');
    console.log(JSON.stringify(stats, null, 2));
  } catch (error) {
    console.error('Error:', error);
  }
}

/**
 * Main demo
 */
async function main() {
  console.log('🚀 Bun Workers Demo\n');
  console.log('This demo shows how to use Bun Workers for parallel execution.');
  console.log('Note: This demo requires a valid ANTHROPIC_API_KEY.\n');

  try {
    // Demo 1: Single Query
    // await demoSingleQuery();

    // Demo 2: Parallel Queries
    // await demoParallelQueries();

    // Demo 3: Statistics
    await demoStatistics();

    console.log('\n✅ Demo completed successfully!');
  } catch (error) {
    console.error('\n❌ Demo failed:', error);
  } finally {
    // Cleanup
    await workerManager.shutdown();
  }
}

// Run demo
main().catch(console.error);

